package com.zhouwr.common.metadata;

import com.alibaba.fastjson.JSON;
import com.zhouwr.common.enums.ModelDataType;
import com.zhouwr.common.metadata.unit.UnifyUnit;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.math.BigDecimal;
import java.math.RoundingMode;


/**
 * @program: forallcn-iotps
 * @description: 单精度浮点
 * @author: zhouwr
 * @create: 2020-11-19 16:20
 * @version：1.0
 **/
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class FloatData extends NumberData<Float>{

    private Integer accuracy = 2;
    private Float value = 0f;
    private ModelDataType type = ModelDataType.FLOAT;

    public FloatData accuracy(Integer accuracy) {
        this.accuracy = accuracy;
        return this;
    }

    @Override
    public Float convert(Object value) {
        this.value = super.convertNumber(value, Number::floatValue);
        return this.value;
    }

    @Override
    public Object format(Object value) {
        Number val = convertNumber(value);
        if (val == null) {
            return super.format(value);
        }
        String scaled = new BigDecimal(val.toString())
                .setScale(accuracy, RoundingMode.HALF_UP)
                .toString();
        return super.format(scaled);
    }

    public static void main(String[] args) {
        FloatData floatData = new FloatData();
        floatData.value = 89f;
        floatData.setMax(100);
        floatData.setMin(10);
        floatData.setUnit(UnifyUnit.meter);
        System.out.println(floatData);
        System.out.println(JSON.toJSON(floatData));
        System.out.println(floatData.convert("999.33"));
        System.out.println(floatData.validate(999));
        System.out.println(JSON.toJSON(floatData));
        System.out.println(floatData.format(99));
    }
}
